<template>
    <div class="app-container">
      <el-row :gutter="24">
        <el-col :span="3">
          <div>
            <span>商品分类</span>
            <el-divider></el-divider>
          </div>
          <div class="head-container">
            <el-input v-model="deptName" placeholder="请输入商品名称" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" />
          </div>
          <div class="head-container">
            <el-tree :data="menuDeptOptions" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current @node-click="handleNodeClick" />
          </div>
        </el-col>

      <el-col :span="21">
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
              <el-form-item label="商品编码" prop="productCode">
                <el-input
                  v-model="queryParams.productCode"
                  placeholder="请输入商品编码"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <!--      <el-form-item label="条形码" prop="barcode">-->
              <!--        <el-input-->
              <!--          v-model="queryParams.barcode"-->
              <!--          placeholder="请输入条形码"-->
              <!--          clearable-->
              <!--          @keyup.enter.native="handleQuery"-->
              <!--        />-->
              <!--      </el-form-item>-->
              <el-form-item label="商品名称" prop="productName">
                <el-input
                  v-model="queryParams.productName"
                  placeholder="请输入商品名称"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="sku编码" prop="skuCode">
                <el-input
                  v-model="queryParams.skuCode"
                  placeholder="请输入sku编码"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="规格型号" prop="productSpec">
                <el-input
                  v-model="queryParams.productSpec"
                  placeholder="请输入规格型号"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label="单位" prop="productUnit">
                <el-select v-model="queryParams.productUnit" placeholder="请选择单位">
                  <el-option v-for="dict in dict.type.wms_product_unit" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="创建时间">
                <el-date-picker
                  v-model="daterangeCreatedAt"
                  style="width: 240px"
                  value-format="yyyy-MM-dd"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :default-time="['00:00:00', '23:59:59']"
                ></el-date-picker>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  plain
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleAdd"
                  v-hasPermi="['system:wmsProducts:add']"
                >新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="success"
                  plain
                  icon="el-icon-edit"
                  size="mini"
                  :disabled="single"
                  @click="handleUpdate"
                  v-hasPermi="['system:wmsProducts:edit']"
                >修改</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="danger"
                  plain
                  icon="el-icon-delete"
                  size="mini"
                  :disabled="multiple"
                  @click="handleDelete"
                  v-hasPermi="['system:wmsProducts:remove']"
                >删除</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="warning"
                  plain
                  icon="el-icon-download"
                  size="mini"
                  @click="handleExport"
                  v-hasPermi="['system:wmsProducts:export']"
                >导出</el-button>
              </el-col>
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>


            <el-table v-loading="loading" :data="wmsProductsList" @selection-change="handleSelectionChange" stripe>
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="商品名称" align="center" prop="productName" />
              <el-table-column label="商品编码" align="center" prop="productCode" />
              <el-table-column label="sku编码" align="center" prop="skuCode" />
              <!--      <el-table-column label="条形码" align="center" prop="barcode" />-->
              <el-table-column label="规格型号" align="center" prop="productSpec" />
              <el-table-column label="单位" align="center" prop="productUnit" >
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.wms_product_unit" :value="scope.row.productUnit">
                  </dict-tag>
                </template>
              </el-table-column>
              <el-table-column label="商品分类" align="center" prop="categoryName" />
              <el-table-column label="品牌" align="center" prop="brandName" />
              <el-table-column label="供应商"  width="100%" align="center" prop="supplierName" />
              <el-table-column label="采购价" align="center" prop="purchasePrice" />
              <el-table-column label="销售价" align="center" prop="sellingPrice" />
              <el-table-column label="批发价" align="center" prop="wholesalePrice" />
              <el-table-column label="保质期(天)"  width="100%"  align="center" prop="shelfLife" />
              <el-table-column label="重量(kg)" align="center" prop="weight" />
              <el-table-column label="体积(m³)" align="center" prop="volume" />
              <el-table-column label="商品描述" align="center" prop="description" :show-overflow-tooltip='true' />
              <el-table-column label="商品图片" align="center" prop="imageUrl" width="100">
                <template slot-scope="scope">
                  <image-preview :src="scope.row.imageUrl" :width="50" :height="50"/>
                </template>
              </el-table-column>
              <el-table-column label="商品二维码" align="center" prop="barcodeImageUrl" width="100">
                <template slot-scope="scope">
                  <image-preview :src="scope.row.barcodeImageUrl" :width="50" :height="50"/>
                </template>
              </el-table-column>
              <el-table-column label="创建时间" align="center" prop="createdAt" width="180">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.createdAt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" :width="150" align="center" fixed="right" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleUpdate(scope.row)"
                    v-hasPermi="['system:wmsProducts:edit']"
                  >修改</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                    v-hasPermi="['system:wmsProducts:remove']"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <pagination
              v-show="total>0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
            />
      </el-col>
    </el-row>




    <!-- 添加或修改商品基础信息对话框 -->
    <el-drawer
      title="新增商品"
      :visible.sync="open"
      direction="rtl"
      custom-class="demo-drawer"
      ref="drawer"
      size="48%"
    >
      <div class="demo-drawer__content">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="商品编码" prop="productCode">
                <el-input v-model="form.productCode" placeholder="请输入商品编码" style="width: 50%"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="商品名称" prop="productName">
                <el-input v-model="form.productName" placeholder="请输入商品名称" style="width: 50%"/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="sku编码" prop="skuCode">
                <el-input v-model="form.skuCode" placeholder="请输入sku编码"  style="width: 50%"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="规格型号" prop="productSpec">
                <el-input v-model="form.productSpec" placeholder="请输入规格型号"  style="width: 50%"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="单位" prop="productUnit" style="width: 65%">
                <el-select v-model="form.productUnit" placeholder="请选择单位">
                  <el-option v-for="dict in dict.type.wms_product_unit" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="商品分类" prop="productCategoryId" style="width: 65%">
                <treeselect v-model="form.productCategoryId" :options="deptOptions" :show-count="false" placeholder="请选择商品分类" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="品牌" prop="productBrandId">
                <el-select v-model="form.productBrandId" placeholder="请选择单位" style="width: 65%" >
                  <el-option v-for="item in this.brandsSelect" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="供应商" prop="supplierId">
                <el-select v-model="form.supplierId" placeholder="请选择供应商" style="width: 65%" >
                  <el-option v-for="item in this.supplierSelect" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="采购价" prop="purchasePrice">
                <el-input v-model="form.purchasePrice" placeholder="请输入采购价" style="width: 50%"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="销售价" prop="sellingPrice">
                <el-input v-model="form.sellingPrice" placeholder="请输入销售价" style="width: 50%"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="批发价" prop="wholesalePrice">
                <el-input v-model="form.wholesalePrice" placeholder="请输入批发价" style="width: 50%"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="保质期(天)" prop="shelfLife">
                <el-input v-model="form.shelfLife" placeholder="请输入保质期(天)" style="width: 50%"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="重量(kg)" prop="weight">
                <el-input v-model="form.weight" placeholder="请输入重量(kg)" style="width: 50%"/>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="体积(m³)" prop="volume">
                <el-input v-model="form.volume" placeholder="请输入体积(m³)" style="width: 50%"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="商品描述" prop="description">
            <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="商品图片" prop="imageUrl">
            <image-upload v-model="form.imageUrl"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" style="text-align: center;">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>

    </el-drawer>
  </div>
</template>

<script>
import { listWmsProducts, getWmsProducts, delWmsProducts, addWmsProducts, updateWmsProducts } from "@/api/system/wmsProducts"
import { getTree } from "@/api/system/wmsProductCategories"
import {getBrandsSelect,getSupplierSelect} from "@/api/system/selectVo";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "WmsProducts",
  dicts: ['wms_product_unit'],
  components: { Treeselect },
  data() {
    return {
      //商品分类树
      deptOptions: [],
      //菜单商品分类树
      menuDeptOptions: [],
      //查询商品品牌下拉框
      brandsSelect: [],
      //供应商下拉框
      supplierSelect: [],
      deptName:undefined,
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品基础信息表格数据
      wmsProductsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 更新时间时间范围
      daterangeCreatedAt: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productCode: null,
        skuCode: null,
        barcode: null,
        productName: null,
        productSpec: null,
        productUnit: null,
        productCategoryId: null,
        productBrandId: null,
        supplierId: null,
        purchasePrice: null,
        sellingPrice: null,
        wholesalePrice: null,
        minStock: null,
        maxStock: null,
        shelfLife: null,
        weight: null,
        volume: null,
        description: null,
        imageUrl: null,
        isActive: null,
        createdAt: null,
        updatedAt: null
      },
      fit:"fit",
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        productCode: [
          { required: true, message: "商品编码不能为空", trigger: "blur" }
        ],
        skuCode: [
          { required: true, message: "sku编码不能为空", trigger: "blur" }
        ],
        productName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        productUnit: [
          { required: true, message: "单位(个/箱/千克等)不能为空", trigger: "blur" }
        ],
        productCategoryId: [
          { required: true, message: "商品分类不能为空", trigger: "blur" }
        ],
        createdAt: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
        updatedAt: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ]
      }
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },

  created() {
    this.getList()
  },
  methods: {
    /** 查询商品基础信息列表 */
    getList() {
      this.loading = true
      this.queryParams.params = {}
      if (null != this.daterangeCreatedAt && '' != this.daterangeCreatedAt) {
        this.queryParams.params["beginCreatedAt"] = this.daterangeCreatedAt[0]
        this.queryParams.params["endCreatedAt"] = this.daterangeCreatedAt[1]
      }
      listWmsProducts(this.queryParams).then(response => {
        this.wmsProductsList = response.rows
        this.total = response.total
        this.loading = false
      })

      //查询商品分类树
      getTree().then(response => {
        //菜单商品分类树
        this.menuDeptOptions = response.data
        //商品分类树
        this.deptOptions = this.menuDeptOptions.filter(item => item.id !== 1);
      })

      //查询商品品牌下拉框
      getBrandsSelect().then(response => {
        this.brandsSelect = response.data
      })

      //查询供应商下拉框
      getSupplierSelect().then(response => {
        this.supplierSelect = response.data
      })

    },

    handleClose(done) {
      if (this.loading) {
        return;
      }
      this.$confirm('确定要提交表单吗？')
        .then(_ => {
          this.loading = true;
          this.timer = setTimeout(() => {
            done();
            // 动画关闭需要一定的时间
            setTimeout(() => {
              this.loading = false;
            }, 400);
          }, 2000);
        })
        .catch(_ => {});
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        productCode: null,
        skuCode: null,
        barcode: null,
        productName: null,
        productSpec: null,
        productUnit: null,
        productCategoryId: null,
        productBrandId: null,
        supplierId: null,
        purchasePrice: null,
        sellingPrice: null,
        wholesalePrice: null,
        minStock: null,
        maxStock: null,
        shelfLife: null,
        weight: null,
        volume: null,
        description: null,
        imageUrl: null,
        isActive: null,
        createdAt: null,
        updatedAt: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreatedAt = []
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加商品基础信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getWmsProducts(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改商品基础信息"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateWmsProducts(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addWmsProducts(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除商品基础信息编号为"' + ids + '"的数据项？').then(function() {
        return delWmsProducts(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/wmsProducts/export', {
        ...this.queryParams
      }, `wmsProducts_${new Date().getTime()}.xlsx`)
    },


    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },

    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.productCategoryId = data.id
      this.handleQuery()
    },
  }
}
</script>
